#include "article-menu-convert.h"

#include "util/logger/logger.h"


static const char *kLineEnd = "\r\n";

namespace book
{

static const char *title() {
    return "ArticleMenuConvert ";
}

ArticleMenuConvert::ArticleMenuConvert(const ArticleMenu &menu, std::ostream &out)
    : menu_(menu), out_(out) {

    if (!out) {
        throw StreamCheckError();
    }
}

void ArticleMenuConvert::operator()() {
    out_ << "<ul>" << kLineEnd;
    for (const ArticleMenu::Node &node : menu_.items()) {
        out_ << "<li>" << kLineEnd;
        out_ << "<a class=\"menu-a\" href=\"#sec" << node.data().sectionId() << "\">" << node.data().title() << "</a>" << kLineEnd;
        convertNestedMenu(node);
        out_ << "</li>" << kLineEnd;
    }
    out_ << "</ul>" << kLineEnd;
}

void ArticleMenuConvert::convertNestedMenu(const ArticleMenu::Node &nestedNode) {
    if (nestedNode.children().empty()) {
        return;
    }

    out_ << "<ul>" << kLineEnd;
    for (const ArticleMenu::Node &n : nestedNode.children()) {
        out_ << "<li>" << kLineEnd;
        out_ << "<a class=\"menu-a\" href=\"#sec" << n.data().sectionId() << "\">" << n.data().title() << "</a>" << kLineEnd;
        convertNestedMenu(n);
        out_ << "</li>" << kLineEnd;
    }
    out_ << "</ul>" << kLineEnd;
}

} // namespace book
